// 汉密尔顿抑郁量表（HAMD）评估逻辑

/**
 * 计算HAMD评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 评估结果
 */
export function calculateHAMDAssessment(formData) {
  // 计算总分
  const totalScore = (
    (formData.depression || 0) +
    (formData.guilt || 0) +
    (formData.suicide || 0) +
    (formData.insomnia_early || 0) +
    (formData.insomnia_middle || 0) +
    (formData.insomnia_late || 0) +
    (formData.work_interests || 0) +
    (formData.retardation || 0) +
    (formData.agitation || 0) +
    (formData.anxiety_psychic || 0) +
    (formData.anxiety_somatic || 0) +
    (formData.somatic_gastrointestinal || 0) +
    (formData.somatic_general || 0) +
    (formData.genital_symptoms || 0) +
    (formData.hypochondriasis || 0) +
    (formData.loss_of_weight || 0) +
    (formData.insight || 0)
  );

  // 生成诊断结果
  let diagnosis = '';
  let severity = '';
  let riskLevel = 'low';

  if (totalScore <= 7) {
    diagnosis = '无抑郁症状';
    severity = '临床痊愈';
    riskLevel = 'low';
  } else if (totalScore >= 8 && totalScore <= 16) {
    diagnosis = '可能存在抑郁症状';
    severity = '轻度抑郁倾向';
    riskLevel = 'medium';
  } else if (totalScore >= 17 && totalScore <= 23) {
    diagnosis = '轻中度抑郁';
    severity = '需要关注和干预';
    riskLevel = 'high';
  } else if (totalScore >= 24) {
    diagnosis = '重度抑郁';
    severity = '需要立即专业治疗';
    riskLevel = 'critical';
  }

  // 生成各项详细结果
  const details = [
    {
      name: '抑郁情绪',
      score: formData.depression || 0,
      maxScore: 4,
      result: getScoreDescription(formData.depression || 0, 4)
    },
    {
      name: '有罪感',
      score: formData.guilt || 0,
      maxScore: 4,
      result: getScoreDescription(formData.guilt || 0, 4)
    },
    {
      name: '自杀',
      score: formData.suicide || 0,
      maxScore: 4,
      result: getScoreDescription(formData.suicide || 0, 4),
      critical: (formData.suicide || 0) >= 2
    },
    {
      name: '入睡困难',
      score: formData.insomnia_early || 0,
      maxScore: 2,
      result: getScoreDescription(formData.insomnia_early || 0, 2)
    },
    {
      name: '睡眠不深',
      score: formData.insomnia_middle || 0,
      maxScore: 2,
      result: getScoreDescription(formData.insomnia_middle || 0, 2)
    },
    {
      name: '早醒',
      score: formData.insomnia_late || 0,
      maxScore: 2,
      result: getScoreDescription(formData.insomnia_late || 0, 2)
    },
    {
      name: '工作和兴趣',
      score: formData.work_interests || 0,
      maxScore: 4,
      result: getScoreDescription(formData.work_interests || 0, 4)
    },
    {
      name: '迟滞',
      score: formData.retardation || 0,
      maxScore: 4,
      result: getScoreDescription(formData.retardation || 0, 4)
    },
    {
      name: '激越',
      score: formData.agitation || 0,
      maxScore: 4,
      result: getScoreDescription(formData.agitation || 0, 4)
    },
    {
      name: '精神性焦虑',
      score: formData.anxiety_psychic || 0,
      maxScore: 4,
      result: getScoreDescription(formData.anxiety_psychic || 0, 4)
    },
    {
      name: '躯体性焦虑',
      score: formData.anxiety_somatic || 0,
      maxScore: 4,
      result: getScoreDescription(formData.anxiety_somatic || 0, 4)
    },
    {
      name: '胃肠道症状',
      score: formData.somatic_gastrointestinal || 0,
      maxScore: 2,
      result: getScoreDescription(formData.somatic_gastrointestinal || 0, 2)
    },
    {
      name: '全身症状',
      score: formData.somatic_general || 0,
      maxScore: 2,
      result: getScoreDescription(formData.somatic_general || 0, 2)
    },
    {
      name: '性症状',
      score: formData.genital_symptoms || 0,
      maxScore: 2,
      result: getScoreDescription(formData.genital_symptoms || 0, 2)
    },
    {
      name: '疑病',
      score: formData.hypochondriasis || 0,
      maxScore: 4,
      result: getScoreDescription(formData.hypochondriasis || 0, 4)
    },
    {
      name: '体重减轻',
      score: formData.loss_of_weight || 0,
      maxScore: 2,
      result: getScoreDescription(formData.loss_of_weight || 0, 2)
    },
    {
      name: '自知力',
      score: formData.insight || 0,
      maxScore: 2,
      result: getScoreDescription(formData.insight || 0, 2)
    }
  ];

  // 检查是否有自杀风险
  const suicideRisk = (formData.suicide || 0) >= 2;
  
  return {
    totalScore,
    maxTotalScore: 52,
    diagnosis,
    severity,
    riskLevel,
    suicideRisk,
    details,
    recommendations: generateRecommendations(totalScore, suicideRisk, formData)
  };
}

/**
 * 获取分数描述
 * @param {number} score - 得分
 * @param {number} maxScore - 最高分
 * @returns {string} 描述
 */
function getScoreDescription(score, maxScore) {
  if (score === 0) {
    return '无症状';
  } else if (score === 1) {
    return '轻度';
  } else if (score === 2) {
    if (maxScore === 2) {
      return '重度';
    } else {
      return '中度';
    }
  } else if (score === 3) {
    return '重度';
  } else if (score === 4) {
    return '极重度';
  }
  return `${score}分`;
}

/**
 * 生成建议
 * @param {number} totalScore - 总分
 * @param {boolean} suicideRisk - 是否有自杀风险
 * @param {Object} formData - 表单数据
 * @returns {Array} 建议列表
 */
function generateRecommendations(totalScore, suicideRisk, formData) {
  const recommendations = [];

  // 自杀风险警告
  if (suicideRisk) {
    recommendations.push({
      type: 'critical',
      title: '⚠️ 自杀风险警告',
      content: '检测到自杀倾向，请立即寻求专业心理健康服务或联系危机干预热线！'
    });
  }

  // 根据总分给出建议
  if (totalScore <= 7) {
    recommendations.push({
      type: 'success',
      title: '✅ 心理状态良好',
      content: '当前无明显抑郁症状，建议保持良好的生活习惯和心理健康维护。'
    });
  } else if (totalScore >= 8 && totalScore <= 16) {
    recommendations.push({
      type: 'warning',
      title: '⚠️ 需要关注',
      content: '存在轻度抑郁倾向，建议：1）调整作息规律；2）增加运动和社交活动；3）必要时咨询心理健康专业人士。'
    });
  } else if (totalScore >= 17 && totalScore <= 23) {
    recommendations.push({
      type: 'danger',
      title: '🔴 需要干预',
      content: '存在轻中度抑郁症状，强烈建议寻求专业心理治疗或精神科医生诊断，考虑心理治疗和/或药物治疗。'
    });
  } else if (totalScore >= 24) {
    recommendations.push({
      type: 'critical',
      title: '🚨 需要立即治疗',
      content: '存在重度抑郁症状，请立即就医！需要专业的精神科医生诊断和治疗，可能需要住院治疗。'
    });
  }

  // 睡眠问题建议
  const sleepScore = (formData.insomnia_early || 0) + (formData.insomnia_middle || 0) + (formData.insomnia_late || 0);
  if (sleepScore >= 3) {
    recommendations.push({
      type: 'info',
      title: '💤 睡眠改善建议',
      content: '检测到明显睡眠问题，建议：1）建立规律作息；2）睡前避免刺激性活动；3）创造良好睡眠环境；4）必要时咨询睡眠专科。'
    });
  }

  // 焦虑症状建议
  const anxietyScore = (formData.anxiety_psychic || 0) + (formData.anxiety_somatic || 0);
  if (anxietyScore >= 4) {
    recommendations.push({
      type: 'info',
      title: '😰 焦虑管理建议',
      content: '检测到明显焦虑症状，建议：1）学习放松技巧（深呼吸、冥想）；2）规律运动；3）避免咖啡因；4）考虑认知行为治疗。'
    });
  }

  return recommendations;
}

/**
 * 生成个人报告
 * @param {Object} surveyData - 问卷数据
 * @param {Object} recorderInfo - 记录人信息
 * @returns {string} 报告内容
 */
export function generateHAMDReport(surveyData, recorderInfo) {
  const timestamp = new Date().toLocaleString('zh-CN');
  const recordTime = surveyData.recordTime ?
    new Date(surveyData.recordTime).toLocaleString('zh-CN') :
    timestamp;

  return `汉密尔顿抑郁量表（HAMD）评估报告
问答编号：${recorderInfo.surveyId}
生成时间：${timestamp}

=== 记录人信息 ===
记录人姓名：${recorderInfo.name}
记录人职务/身份：${recorderInfo.position}
所属机构：${recorderInfo.institution || '未填写'}
联系方式：${recorderInfo.contact || '未填写'}
记录时间：${recordTime}
备注：${surveyData.remarks || '无'}

=== 被评估人基本信息 ===
姓名：${surveyData.patientName}
年龄：${surveyData.age}岁
性别：${surveyData.gender === 'male' ? '男性' : '女性'}
联系电话：${surveyData.phone || '未填写'}

=== 评估结果 ===
总分：${surveyData.totalScore}/52
诊断结果：${surveyData.diagnosis}
严重程度：${surveyData.severity}
${surveyData.suicideRisk ? '⚠️ 存在自杀风险！' : ''}

=== 各项详细结果 ===
${surveyData.details ? surveyData.details.map((item, index) => 
  `${index + 1}. ${item.name}：${item.score}/${item.maxScore}分 (${item.result})${item.critical ? ' ⚠️' : ''}`
).join('\n') : ''}

=== 评分标准 ===
• ≤7分：无抑郁症状，临床痊愈
• 8-16分：可能存在抑郁症状
• ≥17分：判定有抑郁症状
• 18-23分：轻中度抑郁
• ≥24分：重度抑郁

=== 原始评估数据 ===
1. 抑郁情绪：${surveyData.depression || 0}分
2. 有罪感：${surveyData.guilt || 0}分
3. 自杀：${surveyData.suicide || 0}分
4. 入睡困难：${surveyData.insomnia_early || 0}分
5. 睡眠不深：${surveyData.insomnia_middle || 0}分
6. 早醒：${surveyData.insomnia_late || 0}分
7. 工作和兴趣：${surveyData.work_interests || 0}分
8. 迟滞：${surveyData.retardation || 0}分
9. 激越：${surveyData.agitation || 0}分
10. 精神性焦虑：${surveyData.anxiety_psychic || 0}分
11. 躯体性焦虑：${surveyData.anxiety_somatic || 0}分
12. 胃肠道症状：${surveyData.somatic_gastrointestinal || 0}分
13. 全身症状：${surveyData.somatic_general || 0}分
14. 性症状：${surveyData.genital_symptoms || 0}分
15. 疑病：${surveyData.hypochondriasis || 0}分
16. 体重减轻：${surveyData.loss_of_weight || 0}分
17. 自知力：${surveyData.insight || 0}分

报告结束
`;
}